<template>
  <div class="engineering-manager">
    <div class="filter-container">
      <div class="filter-container-select">
        <span>业务类型</span>
        <el-select v-model="tableParams.portaintId" placeholder="请选择" size="large" style="width: 240px">
          <el-option v-for="item in businessTypes" :key="item.portraitId" :label="item.portraitName" :value="item.portraitId" />
        </el-select>
      </div>
      <div class="filter-container-date">
        <el-select placeholder="请选择" v-model="tableParams.dateType" @change="changeTimeType">
          <el-option :value="1" label="开工时间"></el-option>
          <el-option :value="2" label="计划开工时间"></el-option>
          <el-option :value="3" label="计划结束时间"></el-option>
        </el-select>
        <el-date-picker
          v-model="tableParams.daterange"
          :clearable="false"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </div>
      <div class="filter-container-buttons">
        <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
        <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
      </div>
    </div>
    <el-tabs v-model="tableParams.buildState" @tabChange="handelChangeTab">
      <el-tab-pane v-for="item in statusList" :label="item.label" :name="item.value"></el-tab-pane>
    </el-tabs>
    <div class="table-container" element-loading-text="数据加载中..." v-loading="isLoadingTable">
      <div class="table-container-filter">
        <div>
          <el-checkbox label="延期风险" v-model="tableParams.isDelay" />
          <el-checkbox label="只看未完成的" v-model="tableParams.isComplete" />
          <el-checkbox label="收款异常" v-model="payState" />
          <el-checkbox label="未分配" v-model="tableParams.isToBeAllocated" />
        </div>
        <div class="search-container">
          <el-input
            v-model="tableParams.keyWords"
            class="search-input"
            placeholder="请输入"
            :suffix-icon="Search"
            @keyup.enter="handelSearch"
          />
          <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
          <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
        </div>
      </div>
      <!--      <template>-->
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="name" label="客户姓名" fixed="left" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="client-name" @click="handelGoDetail(row)">{{ row.customerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-popover placement="bottom" width="210" trigger="hover">
              <template #reference>
                <span style="cursor: default">{{ showPrincipalLabel(row).value }}</span>
              </template>
              <div class="user-info" v-show="row.principalList">
                <div class="user-info-item" v-for="item in principalList(row).value" :key="item.userId">
                  <span>{{ item.roleName }}</span>
                  <span style="margin: 0 5px">:</span>
                  <span class="user-info-item__name">{{ item.userName }}</span>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="portaintName" label="业务类型" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="address" label="项目地址" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="status-tag" :class="`status-tag-${statusLabel(row).value[0]}`">{{ statusLabel(row).value[1] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="进度" width="300">
          <template #default="{ row }">
            <div class="table-container-schedule">
              <span>{{ row.currentTaskName }}</span>
              <el-progress
                :text-inside="true"
                :stroke-width="26"
                :percentage="percentage(row).value"
                color="#0052D9"
                style="margin-left: 8px; width: 100px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="正在整改/增减项" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button v-if="row.ingReform" type="danger" link @click="handelGoDetail(row, 'rectification')"
              >{{ row.ingReform }}个
            </el-button>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="收款计划" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.factMoney && row.planMoney && row.paymentStatus != 0">
              <span class="payment-plan" v-if="row.paymentStatus != 3" @click="handelGoDetail(row, 'paymentPlan')"
                >{{ row.factMoney }}/{{ row.planMoney }}</span
              >
              <span class="payment-plan red-color" v-else @click="handelGoDetail(row, 'paymentPlan')"
                >{{ row.factMoney }}/{{ row.planMoney }}</span
              >
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="下次计划收款" width="220" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.collectPlanName">
              <span>{{ row.collectPlanName }}：￥{{ row.nextTaskPlanMoney }}</span
              ><br />
              <span>预计收款日期：{{ row.nextPlanCompleteTime }}</span
              ><br />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="验收计划" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <template v-if="row.isCraft">
              <span class="client-name" style="margin-right: 10px" @click="handelGoDetail(row, 'acceptancePlan')"
                >{{ row.passNumber }}/{{ row.totalNumber }}</span
              >
              <span style="color: #bebebe">已设置</span>
            </template>
            <span v-else class="client-name" @click="handelGoDetail(row, 'acceptancePlan')">设置工艺</span>
          </template>
        </el-table-column>
        <el-table-column label="计划周期" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.plainDays">{{ row.plainDays }}天</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="实际周期" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.isDelay || row.isExceed" style="color: red">{{ row.factCycle }}</span>
            <span v-else>{{ row.factCycle || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minFactStartDate" label="开工时间" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="maxPlainEndDate" label="计划完工时间" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="maxFactEndDate" label="实际完工时间" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <div class="table-operate">
              <el-button v-for="button in getVisibleButtons(row)" :key="button.text" type="primary" link @click="button.action">
                {{ button.text }}
              </el-button>
              <div v-if="showDropdownitem(row)">
                <el-dropdown>
                  <span class="el-dropdown-link" style="font-size: 14px"
                    >展开
                    <el-icon class="el-icon--left">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-for="item in filteredDropdownItems(row)"
                        :key="item.command"
                        :command="item.command"
                        @click="item.action"
                      >
                        <el-button type="text" style="height: 22px">{{ item.text }}</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--      </template>-->
      <!--      <el-empty v-else />-->
    </div>
    <custom-pagination
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, slot, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>

    <!--  结案  -->
    <div class="client-del-dialog">
      <el-dialog v-model="isDeleteClient" width="400" :align-center="true" :show-close="false" :close-on-click-modal="false">
        <div class="client-del-name">{{ clientInfo.customerName }}</div>
        <div class="client-del-tip">是否将该工地进行结案？结案后不可再调整相关数据！</div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handelDelClose" size="default">取消</el-button>
            <el-button type="primary" @click="handelDelSubmit" :loading="isDelLoading" size="default">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 发起整改增减项   -->
    <div class="delete-dialog">
      <el-dialog :show-close="false" v-model="visible" :title="`创建${nameTitle}售后单`" width="450px" center>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
          <el-form-item :label="`请选择${nameTitle}关联的合同`" prop="contractId">
            <el-select v-model="ruleForm.contractId" class="m-2" placeholder="请选择" clearable @change="handleChange">
              <el-option v-for="item in associatedContract" :key="item.contractId" :label="item.title" :value="item.contractId" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否创建报价变更单" prop="radio">
            <el-radio-group v-model="ruleForm.radio" class="ml-4">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="2" size="large" :disabled="nameTitle.value !== '整改'">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleGotoAdd">下一步</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onActivated } from "vue";
import { ArrowDown, RefreshRight, Search } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { portraitList } from "@/apis/dict/dict";
import { engineeringList, closeCase, contractList } from "@/apis/engineeringManager";
import { statusList } from "./config";
import { tableRowClassName } from "../utils";
import useComputedParams from "@/hooks/useComputedParams";
import { dayjs, ElMessage } from "element-plus";
import { resetClientInfo } from "@/apis/clientManager";
import useTagsViewStore from "@/store/modules/tagsView";
import { checkReform } from "@/apis/template";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const tagsViewStore = useTagsViewStore();
const isLoadingTable = ref(false);
const showNo = ref(false);
const ruleFormRef = ref();
const associatedContract = ref([]); // 关联的合同
const visible = ref(false);
const ruleForm = ref({
  radio: 2,
  contractId: ""
});
const rules = ref({
  radio: {
    required: true,
    message: "请选择",
    trigger: "change"
  },
  contractId: {
    required: true,
    message: "请选择关联的合同",
    trigger: "change"
  }
});
const initTableParams = {
  current: 1,
  size: 10,
  dateType: 1,
  portaintId: "",
  isDelay: false,
  isComplete: true,
  keyWords: "",
  buildState: 0,
  daterange: [],
  startWorkDate: "",
  startEndDate: "",
  isToBeAllocated: false
};
const payState = ref(false);
const tableParams = ref({ ...initTableParams });
const tableData = ref([]);
const listTotal = ref(0);
const businessTypes = ref([]);
const nameTitle = ref("");
const customerId = ref("");
const statusMap = new Map([
  [1, ["info", "未开始"]],
  [2, ["primary", "进行中"]],
  [3, ["success", "已完成"]],
  [4, ["info", "已结案"]],
  [5, ["danger", "停工"]]
]);
const buttons = row => {
  return [
    {
      command: 0,
      condition: () => true,
      text: "详情",
      action: () => handelGoDetail(row, "constructionPlan")
    },
    {
      command: 1,
      condition: () => ![3, 4].includes(row.status),
      text: "分配",
      action: () => handelDistribution(row)
    },
    {
      command: 2,
      condition: () => row.status === 3,
      text: "结案",
      action: () => handelEnd(row)
    },
    {
      command: 3,
      condition: () => true,
      text: "重置任务",
      action: () => handelResetTask(row)
    },
    {
      command: 4,
      condition: () => row.status !== 4,
      text: "发起整改",
      action: () => handleCommand(1, row)
    },
    {
      command: 5,
      condition: () => row.status !== 4,
      text: "发起增减项",
      action: () => handleCommand(3, row)
    }
  ];
};
//定义按钮
const getVisibleButtons = row => {
  // 过滤可见按钮
  const filteredButtons = buttons(row).filter(btn => btn.condition());
  return filteredButtons.length <= 2 ? filteredButtons : [filteredButtons[0]];
};
//判断按钮显示个数是否大于2 大于2返回true
const showDropdownitem = row => {
  const arryButtonCount = buttons(row).reduce((count, item) => count + item.condition(), 0);
  return arryButtonCount > 2;
};
// 过滤掉第一个满足条件的下拉项
const filteredDropdownItems = row => {
  const visibleItems = buttons(row).filter(item => item.condition());
  visibleItems.shift();
  return visibleItems;
};
// 发起整改增减项
const handleCommand = (command, row) => {
  nameTitle.value = command === 1 ? "整改" : "增减项";
  customerId.value = row.customerId;
  ruleForm.value = {
    radio: 2,
    contractId: ""
  };
  getContractList(row);
};
// 获取关联合同
const getContractList = async row => {
  const { data } = await contractList({ customerId: row.customerId });
  associatedContract.value = data || [];
  if (data.length > 0) {
    visible.value = true;
    if (nameTitle.value === "增减项") {
      ruleForm.value.radio = 1;
      showNo.value = true;
    } else {
      showNo.value = false;
    }
    if (data.length === 1) {
      ruleForm.value = { ...ruleForm.value, ...data[0] };
    } else {
      ruleForm.value.contractId = "";
    }
  } else {
    if (nameTitle.value === "增减项") {
      ElMessage.error("该客户无合同，不可发起增减项");
    } else {
      await router.push({
        path: "/after-sales-order",
        query: {
          budgetId: ruleForm.value.budgetId,
          customerId: customerId.value,
          afterSalesType: 1
        }
      });
    }
  }
};

// 选择关联合同
const handleChange = contractId => {
  const customerObj = associatedContract.value.find(item => item.contractId === contractId);
  if (customerObj.contractId) {
    ruleForm.value = {
      ...ruleForm.value,
      ...customerObj
    };
  }
};
// 创建增减项整改
const handleGotoAdd = async () => {
  ruleFormRef.value.validate(async valid => {
    if (!valid) return;
    //是否创建预算报价增减项单 1是 2否
    if (ruleForm.value.radio === 1) {
      const { data } = await checkReform(ruleForm.value.contractId);
      if (data !== true) {
        ElMessage.error("存在进行中的变更单，无法再次发起！");
        return true;
      }
      const afterSalesType = nameTitle.value === "整改" ? 1 : 3;
      const baseRouter = window.microApp.router.getBaseAppRouter();
      const routeUrl = baseRouter.resolve({
        path: "/designer/quote-price/following/change",
        query: {
          budgetId: ruleForm.value.budgetId,
          contractId: ruleForm.value.contractId,
          customerId: customerId.value,
          afterSalesType
        }
      });
      window.open(routeUrl.href, "_blank");
      visible.value = false;
    } else {
      await router.push({
        path: "/after-sales-order",
        query: {
          budgetId: ruleForm.value.budgetId,
          contractId: ruleForm.value.contractId,
          customerId: customerId.value,
          afterSalesType: nameTitle.value === "整改" ? 1 : 3
        }
      });
      visible.value = false;
    }
  });
};
const statusLabel = useComputedParams(data => {
  return statusMap.has(data.status) ? statusMap.get(data.status) : ["info", "未知"];
});
const percentage = useComputedParams(data => {
  const num = data.allExecuteDays ? parseFloat((data.completeExecuteDays / data.allExecuteDays).toFixed(2)) : 0;
  const accMul = (arg1, arg2) => {
    let m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) {}
    try {
      m += s2.split(".")[1].length;
    } catch (e) {}
    return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
  };
  return accMul(parseFloat(num), 100);
});
const showPrincipalLabel = useComputedParams(data => {
  const list = data.principalList?.length ? data.principalList.slice(0, 3) : [];
  return list
    .map(item => item.userName)
    .filter(Boolean)
    .join(",");
});
const principalList = useComputedParams(data => {
  return data.principalList?.filter(item => item.roleName && item.userName)?.map(item => ({ ...item })) || [];
});

const changeTimeType = () => {
  tableParams.value.daterange = [];
  tableParams.value.startWorkDate = "";
  tableParams.value.startEndDate = "";
};

const getEngineeringList = async () => {
  try {
    isLoadingTable.value = true;
    if (tableParams.value?.daterange?.length >= 2) {
      tableParams.value.startWorkDate = tableParams.value.daterange[0];
      tableParams.value.startEndDate = tableParams.value.daterange[1];
    }
    tableParams.value.payState = payState.value ? 3 : "";
    const { data } = await engineeringList(tableParams.value);
    tableData.value =
      data.list?.map(item => {
        return {
          ...item,
          minFactStartDate: item.minFactStartDate ? dayjs(item.minFactStartDate).format("YYYY-MM-DD") : "--",
          maxPlainEndDate: item.maxPlainEndDate ? dayjs(item.maxPlainEndDate).format("YYYY-MM-DD") : "--",
          maxFactEndDate: item.maxFactEndDate ? dayjs(item.maxFactEndDate).format("YYYY-MM-DD") : "--"
        };
      }) || [];
    listTotal.value = data?.total ?? 0;
    isLoadingTable.value = false;
  } catch (err) {
    isLoadingTable.value = false;
  }
};

const getPortraitList = async () => {
  const { data } = await portraitList();
  businessTypes.value = data ?? [];
};

const handelSearch = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getEngineeringList();
};
const handelResetFilter = () => {
  tagsViewStore.isRefresh = false;
  tableParams.value = {
    ...initTableParams
  };
  payState.value = "";
  getEngineeringList();
};
const handelChangeTab = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getEngineeringList();
};
const handelPage = () => {
  tableData.value = [];
  getEngineeringList();
};

const handelGoDetail = (data, funcTab) => {
  router.push({
    path: "/client-info",
    query: {
      funcTab,
      customerId: data.customerId,
      afterSalesType: data.afterSalesType
    }
  });
};
const handelDistribution = data => {
  router.push({
    path: "/distribution",
    query: {
      customerId: data.customerId,
      reformType: false,
      stageType: 2
    }
  });
};

/**
 * 结案
 */
const isDeleteClient = ref(false);
const isDelLoading = ref(false);
const clientInfo = ref({});
const handelEnd = data => {
  isDeleteClient.value = true;
  clientInfo.value = { ...data };
};
const handelDelSubmit = async () => {
  try {
    isDelLoading.value = true;
    await closeCase(clientInfo.value.customerId);
    isDeleteClient.value = false;
    proxy.$modal.msgSuccess("操作成功");
    getEngineeringList();
  } catch (err) {
    isDelLoading.value = false;
  }
};
const handelDelClose = () => {
  isDeleteClient.value = false;
  clientInfo.value = {};
};

//重置任务
const handelResetTask = data => {
  proxy.$modal
    .confirm("除该客户已完成的任务外，其他任务将按最新流程模板重发，是否确认？", "确认操作？")
    .then(async () => {
      try {
        isLoadingTable.value = true;
        await resetClientInfo(data.customerId);
        isLoadingTable.value = false;
        proxy.$modal.msgSuccess("重置成功");
      } catch (err) {
        isLoadingTable.value = false;
      }
    })
    .catch(() => {});
};

const initData = () => {
  tableParams.value.isToBeAllocated = route.query?.unAssigned == 1;
  tagsViewStore.isRefresh = false;
  getPortraitList();
  getEngineeringList();
};

onActivated(() => {
  tagsViewStore.isRefresh && handelResetFilter();
});
initData();
</script>

<style scoped lang="scss">
@use "engineeringManager";
</style>
